import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_utils/flutter_baidu_mapapi_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/member_service.dart';
import 'package:flutter_oldman_health/models/distance_limit_model.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/pages/map/map_setting_page.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';
import 'package:flutter_oldman_health/widget/map_function_select_widget.dart';
import 'map_base_page_state.dart';

/// 地图类型示例
// ignore: must_be_immutable
class ShowMapTypePage extends StatefulWidget {
  BMFMapOptions customMapOptions;
  FamilyRelationItem relationItem;

  // 城市经纬度 老人位置
  BMFCoordinate geoPt = BMFCoordinate(31.185044, 121.584797);

  ShowMapTypePage(
      {Key key, this.customMapOptions, this.relationItem, this.geoPt})
      : super(key: key);

  @override
  ShowMapTypePageState createState() => ShowMapTypePageState();
}

class ShowMapTypePageState extends BMFBaseMapState<ShowMapTypePage> {
  BMFMapType mapType = BMFMapType.Standard;
  BMFCoordinate selectGeoPt;

  MapFunctionSelectWidget mapTypeSelectWidget;
  Map<String, BMFUserTrackingMode> localTypeMap = {
    "标准模式": BMFUserTrackingMode.None,
    "跟随模式": BMFUserTrackingMode.Follow,
    "罗盘模式": BMFUserTrackingMode.FollowWithHeading
  };

  bool showMapSetting = false;
  BMFCircle _circle;
  DistanceLimitItem distanceLimitItem = DistanceLimitItem();
  List<String> expandTypeSelectList = [];//"3D楼宇"
  String mapTypeString = "普通地图";
  String localTypeString = "";

  void queryDistanceLimitList() async {
    var response = await FamilyMemberService.queryDistanceLimitList(
        widget.relationItem.memberId);
    if (null != response && response.statusCode == 200) {
      DistanceLimitModel dataModel = DistanceLimitModel.fromJson(response.data);
      if (null != dataModel && dataModel.success()) {
        updateDistanceLimit(dataModel);
      }
    }
  }

  void updateDistanceLimit(DistanceLimitModel dataModel) {
    if (dataModel.data != null && dataModel.data.length > 0) {
      distanceLimitItem = dataModel.data[0];
      print(
          "queryDistanceLimitList-${distanceLimitItem.latitude} , ${distanceLimitItem.longitude}");
      selectGeoPt = BMFCoordinate(
          distanceLimitItem.latitude, distanceLimitItem.longitude);
      // rangeNum = distanceLimitItem.distance;
      if (_circle == null || _circle.center == null) {
        print("queryDistanceLimitList-1 ");
        addCircle(selectGeoPt);
      } else {
        updateCircle();
      }
    } else {
      distanceLimitItem = DistanceLimitItem();
      distanceLimitItem.distance = 1000;
    }
  }

  void updateCircle() {
    if (Platform.isIOS) {
      _circle.updateHollowShapes([]); // 更新半径先去掉镂空，镂空面积比circle大时会有问题
      //_circle.update Center(selectGeoPt);安卓没有更新,所以区别对待
    }
    print(
        "queryDistanceLimitList2 -${selectGeoPt.latitude} , ${selectGeoPt.longitude}");
    _circle.updateCenter(selectGeoPt).then((value) {
      if (!value) {
        myMapController.removeOverlay(_circle.Id).then((value) {
          print("queryDistanceLimitList211-$value");
          addCircle(selectGeoPt);
        });
      }
    });
    _circle.updateRadius(double.parse(distanceLimitItem.distance.toString()));
  }

  @override
  void initState() {
    super.initState();
    selectGeoPt = widget.geoPt;
    queryDistanceLimitList();
    Future<int> futureInt =
        Utils.getIntSharePreferences("area_protection_distance");
    futureInt.then((value) {
      if (null != value) {
        setState(() {
          distanceLimitItem.distance = value;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return MaterialApp(
        home: Scaffold(
            body: WillPopScope(
                onWillPop: () async {
                  if (showMapSetting) {
                    setState(() {
                      showMapSetting = false;
                    });
                    return false;
                  }
                  Navigator.pop(
                    context,
                  );
                  // myMapController.removeMarker(marker);
                  return false;
                },
                child: Container(
                    color: Constant.backgroundColor,
                    child: Column(
                      children: [
                        Expanded(
                            flex: 1,
                            child: Stack(children: <Widget>[
                              generateMap(),
                              generateControlBar(),
                              _getTitle(widget.relationItem.alias),
                              Align(
                                alignment: Alignment.bottomLeft,
                                child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      GestureDetector(
                                        behavior: HitTestBehavior.translucent,
                                        onTap: () {
                                          mapSetting();
                                        },
                                        child: CommonContainer(
                                            Text(
                                              "区域防护",
                                              style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 17),
                                            ),
                                            margin: EdgeInsets.fromLTRB(
                                                4, 0, 4, 20),
                                            padding: EdgeInsets.fromLTRB(
                                                16, 6, 16, 6),
                                            colorBg: Colors.orange),
                                      ),
                                      Container(
                                        child: GestureDetector(
                                          behavior: HitTestBehavior.translucent,
                                          onTap: () {
                                            onOpenBaiduNaviNative();
                                          },
                                          child: CommonContainer(
                                              Text(
                                                " 导 航 ",
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 17),
                                              ),
                                              margin: EdgeInsets.fromLTRB(
                                                  4, 0, 4, 20),
                                              padding: EdgeInsets.fromLTRB(
                                                  16, 6, 16, 6),
                                              colorBg: Colors.green),
                                        ),
                                      )
                                    ]),
                              )
                            ]))
                      ],
                    )))));
  }

  @override
  Widget generateControlBar() {
    mapTypeSelectWidget =
        MapFunctionSelectWidget(this, mapTypeString, expandTypeSelectList);
    return showMapSetting
        ? Container(
            width: screenSize.width,
            child: Container(
                color: Color(0xddffffff),
                padding:
                    EdgeInsets.only(left: 16, right: 16, bottom: 16, top: 105),
                child: showMapSetting ? mapTypeSelectWidget : null))
        : Padding(padding: EdgeInsets.all(8));
  }

  /// 设置地图参数
  @override
  BMFMapOptions initMapOptions() {
    if (null != widget.customMapOptions) {
      return widget.customMapOptions;
    }
    BMFCoordinate center = widget.geoPt;
    BMFMapOptions mapOptions = BMFMapOptions(
        mapType: mapType,
        zoomLevel: 14,
        maxZoomLevel: 21,
        minZoomLevel: 4,
        logoPosition: BMFLogoPosition.LeftBottom,
        mapPadding: BMFEdgeInsets(top: 0, left: 50, right: 50, bottom: 0),
        overlookEnabled: true,
        overlooking: -15,
        center: center);
    return mapOptions;
  }

  void addCircle(BMFCoordinate bmfCoordinate) {
    _circle = BMFCircle(
      center: bmfCoordinate,
      radius: double.parse(distanceLimitItem.distance.toString()),
      width: 2,
      strokeColor: Colors.redAccent.withAlpha((255 * 0.3).toInt()),
      fillColor: Colors.red.withAlpha((255 * 0.3).toInt()),
      lineDashType: BMFLineDashType.LineDashTypeNone,
    );

    myMapController.addCircle(_circle);
    myMapController.updateMapOptions(BMFMapOptions(
      center: bmfCoordinate,
      mapType: mapType,
      zoomLevel: distanceLimitItem.distance > 1000 ? 14 : 15,
    ));
  }

  void removeCircle() {
    if (_circle != null) {
      myMapController.removeOverlay(_circle.Id);
      _circle = null;
    }
  }

  void setMapTypeString(String type) {
    myMapController.updateMapOptions(BMFMapOptions(
        mapType: type == "普通地图" ? BMFMapType.Standard : BMFMapType.Satellite));
    setState(() {
      print("ssssss33333");

      mapTypeString = type;
      this.mapType =
          type == "普通地图" ? BMFMapType.Standard : BMFMapType.Satellite;
    });
  }

  void setLocalTypeString(String type) {
    if (null != type) {
      myMapController.setUserTrackingMode(localTypeMap[type],
          enableDirection: false);

      if (BMFUserTrackingMode.Follow == localTypeMap[type] ||
          BMFUserTrackingMode.Heading == localTypeMap[type]) {
        myMapController.setNewMapStatus(
            mapStatus: BMFMapStatus(fOverlooking: 0));
      }
    } else {
      myMapController.setUserTrackingMode(BMFUserTrackingMode.None,
          enableDirection: false);
    }
  }

  void setExpandTypeSelectList(List<String> type) {
    if (null != type && type.length > 0) {
      print(type);
      myMapController.updateMapOptions(BMFMapOptions(
          // buildingsEnabled: type.contains("3D楼宇"),
          baiduHeatMapEnabled: type.contains("热力图"),
          trafficEnabled: type.contains("路况图"),
          // showMapPoi: true,
          zoomLevel: 18,
          overlookEnabled: true,
          overlooking: -30));

    } else {
      myMapController.removeHeatMap();
      myMapController.updateMapOptions(BMFMapOptions(
          buildingsEnabled: false,
          trafficEnabled: false,
          // showMapPoi: true,
          zoomLevel: 14,
          overlookEnabled: true,
          overlooking: -30));
    }
    expandTypeSelectList = type;
  }

  void onOpenBaiduNaviNative() async {
    print("onOpenBaiduNaviNative enter");
    // print("baiduLocation ${baiduLocation.latitude},${baiduLocation.longitude}");
    // // 当前位置
    // BMFCoordinate coordinate1 =
    //     BMFCoordinate(baiduLocation.latitude, baiduLocation.longitude);
    String startName = "当前位置";
    // 百度大厦坐标
    String endName = widget.relationItem.alias;
    BMFCoordinate coordinate2 =
        BMFCoordinate(widget.geoPt.latitude, widget.geoPt.longitude);

    BMFOpenNaviOption naviOption = BMFOpenNaviOption(
        // startCoord: coordinate1,
        endCoord: coordinate2,
        startName: startName,
        endName: endName,
        naviType: BMFNaviType.ARWalkNavi,
        //https://juejin.cn/post/6844904185540902919
        // appScheme: 'flutter_oldman_health://flutter_oldman_health',
        // // 指定返回自定义scheme
        // appName: 'flutter_oldman_health',
        // 应用名称
        isSupportWeb:
            true); // 调起百度地图客户端驾车导航失败后（步行、骑行导航设置该参数无效），是否支持调起web地图，默认：true

    BMFOpenErrorCode flag = await BMFOpenMapUtils.openBaiduMapNavi(naviOption);

    if (flag == BMFOpenErrorCode.NOT_SUPPORT) {
      EasyLoading.showInfo("没有安装百度地图，或者版本太低");
    } else if (flag == BMFOpenErrorCode.ROUTE_END_ERROR) {
      EasyLoading.showInfo("路线终点有误");
    } else if (flag == BMFOpenErrorCode.KEY_ERROR) {
      EasyLoading.showInfo("app key错误");
    }
    print("open - nav - errorCode = $flag");
  }

  /// 创建完成回调
  @override
  void onBMFMapCreated(BMFMapController controller) {
    super.onBMFMapCreated(controller);
    if (distanceLimitItem.id != null) {
      addCircle(selectGeoPt);
    }

    /// 地图加载回调
    myMapController.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
      myMapController.showUserLocation(true);
      updateUserLocation();
      myMapController.setUserTrackingMode(BMFUserTrackingMode.Follow);
    });

    myMapController.addMarker(BMFMarker(
        position: widget.geoPt,
        title: '',
        subtitle: '',
        identifier: 'flutter_marker',
        icon: 'images/icon_binding_point.png',
        enabled: false,
        draggable: false));
  }

  Widget _getTitle([String title = "地址信息"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 16),
        child: FractionallySizedBox(
            widthFactor: 1,
            child: Stack(alignment: Alignment.center, children: [
              Positioned(
                  left: 2,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        if (showMapSetting) {
                          setState(() {
                            showMapSetting = false;
                          });
                        } else {
                          Navigator.pop(context);
                          //myMapController.removeMarker(marker);
                        }
                      },
                      child: Container(
                          child: Icon(Icons.arrow_back_ios),
                          padding: EdgeInsets.fromLTRB(15, 10, 20, 10)))),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
              Positioned(
                  right: 2,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        setState(() {
                          showMapSetting = !showMapSetting;
                        });
                        // editFamilyMemberDialog().then((value) {
                        //   print(value);
                        // });
                      },
                      child: Container(
                          padding: EdgeInsets.fromLTRB(8, 2, 8, 2),
                          child: Text("设置",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 18,
                                  fontWeight: FontWeight.normal)),
                          decoration: BoxDecoration(
                              color: Color(0xff41BAB0),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8))))))
            ])));
  }

  void mapSetting() {
    if (distanceLimitItem.latitude == null) {
      distanceLimitItem.latitude = selectGeoPt.latitude;
      distanceLimitItem.longitude = selectGeoPt.longitude;
    }
    Future<BMFCoordinate> r = Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) =>
                MapSettingPage(distanceLimitItem, widget.relationItem)));

    if (null == r) {
      print('mapSetting-地图加载完成');
      return;
    } else {
      r.then((bmfc) async {
        if (null != bmfc && bmfc is BMFCoordinate)
          print(
              "queryDistanceLimitList2ss-${bmfc.latitude} , ${bmfc.longitude}");
        int value =
            await Utils.getIntSharePreferences("area_protection_distance");
        if (value > 0) {
          queryDistanceLimitList();
        } else if (value < 0) {
          removeCircle();
          setState(() {
            distanceLimitItem.remind = 0;
            distanceLimitItem.id = null;
          });
        }
      });
    }
  }
}
